import { getUserPermissionsApi } from '@/api'
import useUserStore from '@/stores/user'
import type { Permission } from '@/types/rbac'
import type { Router, RouteRecordSingleViewWithChildren } from 'vue-router'

// 动态加载组件
const components = import.meta.glob('@/views/**/*.vue')

/**
 * 加载动态路由
 * @param router 路由实例
 * @returns 是否加载成功
 */
export async function loadDynamicRoutes(router: Router): Promise<boolean> {
  try {
    const userStore = useUserStore()
    const userId = userStore.userInfo?.id

    if (!userId) {
      return false
    }
    // 获取用户权限树
    try {
      const res = await getUserPermissionsApi(userId)
      const permissions = res.data
      if (!permissions || typeof permissions !== 'object') {
        return false
      }
      userStore.setPermissions(permissions)
      // 转换为路由
      const dynamicRoutes = transformPermissionsToRoutes(permissions)
      dynamicRoutes.forEach((route) => {
        router.addRoute('layout', route)
      })
      return true
    } catch (error) {
      return false
    }
  } catch (error) {
    console.warn('加载动态路由失败:', error)
    return false
  }
}

/**
 * 将权限树转换为路由
 * @param permissions 权限树
 * @returns 路由数组
 */
function transformPermissionsToRoutes(permissions: Permission[]): RouteRecordSingleViewWithChildren[] {
  return permissions
    .filter((p) => p.type === 'menu' && p.status === 1)
    .map((p) => {
      const route: RouteRecordSingleViewWithChildren = {
        path: p.path,
        name: p.name,
        meta: {
          title: p.label,
          icon: p.icon,
          hidden: p.hidden || false,
        },
        children: [],
      }

      // 如果有组件路径，则设置组件
      if (p.component) {
        route.component = loadComponent(p.component)
      }

      // 如果有重定向，则设置重定向
      if (p.redirect) {
        route.redirect = p.redirect
      }

      // 如果有子权限，则递归处理
      if (p.children && p.children.length > 0) {
        route.children = transformPermissionsToRoutes(p.children)
      }

      return route
    })
}

/**
 * 加载组件
 * @param path 组件路径
 * @returns 组件
 */
function loadComponent(path: string) {
  let res
  for (const c in components) {
    const dir = c.split('views/')[1].split('.vue')[0]
    if (dir === path) {
      res = components[c]
    }
  }
  return res
}
